<template>
  <!-- <div > -->
    <el-tabs v-model="activeTab" style="width: 1200px;
    height:auto;
    min-height: 800px;
    margin: 0 auto;
    margin-top: 20px;
    overflow-y: hidden;
    padding-left: calc(100vw - 100%);
    background-color: rgba(255, 255, 255, 0.37);">
      <el-tab-pane   label="加入社团申请" name="joinClub">
        <div v-if="loading1">数据加载中...</div>
        <div v-if="!loading1">
          <div v-if="joinClubApplies.length>0" style="display: flex;flex-direction: column;">
            <div style="display: flex;justify-content:flex-start;align-items:center;margin:10px">
              <div style="margin-left:10px;margin-right:10px ">
                <el-select v-model="ApprovalState1" placeholder="未审批" @change="getjoinClubApplies" style="width:150px;marigin:10px">
                  <el-option label="未审批" :value="0"></el-option>
                  <el-option label="已审批" :value="1"></el-option>
                </el-select>
              </div>
              <el-button v-if="ApprovalState1 === 0" type="primary" @click="approveSelectedApplies('approve',0)">一键批准所选</el-button>
              <el-button v-if="ApprovalState1 === 0" type="primary" @click="approveSelectedApplies('reject',0)">一键拒绝所选</el-button>
            </div>
            <el-table
                ref="joinClubTable"
                :data="filteredjoinClub"
                :default-sort="{ prop: 'applyTime', order: 'descending' }"
                style="width: 1150px"
            >
              <el-table-column type="selection" width="55" v-if="ApprovalState1 === 0"></el-table-column>
              <el-table-column type="index" width="50">
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" sortable :formatter="DatetoUser"></el-table-column>
              <el-table-column prop="uid" label="用户ID" ></el-table-column>
              <el-table-column prop="uname" label="用户名" width="90"></el-table-column>
              <el-table-column prop="cname" label="社团" :filters="clubFilters1" :filter-method="filterByClub1">
                <template #default="scope">
                  <span>{{ scope.row.cname }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="申请理由"></el-table-column>
              <el-table-column label="申请附件">
                <template #default="{ row }">
                  <div style="display: flex;align-items:center;">
                    <el-icon><Document /></el-icon>
                    <a :href=row.file.FileUrl  @click.prevent="handleDownload(row.file.FileUrl, row.file.Filename)">{{ row.file.Filename }}</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="ApprovalState1 === 0">
                <template v-slot="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-button @click="openDialog1(row, 'approve')" type="primary">批准</el-button>
                    <el-button @click="openDialog1(row, 'reject')" type="danger">拒绝</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="审批结果" v-if="ApprovalState1 === 1" :filters="approvalFilters"
                               :filter-method="filterByApprovalResult">
                <template v-slot="{ row }">
                  <el-tag v-if="row.approval_state === 1" type="success">已通过</el-tag>
                  <el-tag v-if="row.approval_state === 2" type="danger">已拒绝</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog   v-model="dialogVisible1"  title="备注" @close="handleclose">
              <el-input type="textarea" v-model="joinclub.remark"></el-input>
              <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancelJoinClubApprove">取 消</el-button>
                <el-button type="primary" @click="submitForm1">确 定</el-button>
              </span>
              </template>
            </el-dialog>
          </div>
          <div v-else>
            暂时没有入社申请
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="加入活动申请" >
        <div v-if="loading2">数据加载中...</div>
        <div v-if="!loading2">
          <div v-if="joinActivityApplies.length>0" style="display: flex;flex-direction: column;">
            <div style="display: flex;justify-content:flex-start;align-items:center;margin:10px">
              <div style="margin-left:10px;margin-right:10px ">
                <el-select v-model="ApprovalState2"  placeholder="未审批" @change="getJoinActivityApplies"  style="width:150px;marigin:10px">
                  <el-option label="未审批" :value="0"></el-option>
                  <el-option label="已审批" :value="1"></el-option>
                </el-select>
              </div>
              <el-button v-if="ApprovalState2 === 0" type="primary" @click="approveSelectedApplies('approve',1)">一键批准所选</el-button>
              <el-button v-if="ApprovalState2 === 0" type="primary" @click="approveSelectedApplies('reject',1)">一键拒绝所选</el-button>
            </div>

            <el-table
                ref="joinActivityTable"
                :data="filteredjoinActivity"
                :default-sort="{ prop: 'applyTime', order: 'descending' }"
                style="width: 1120px"
            >
              <el-table-column type="selection" width="55" v-if="ApprovalState2 === 0"></el-table-column>
              <el-table-column
                  type="index"
                  width="50">
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" sortable :formatter="DatetoUser"></el-table-column>
              <el-table-column prop="uid" label="用户ID" ></el-table-column>
              <el-table-column prop="uname" label="用户名" ></el-table-column>
              <el-table-column prop="aname" label="活动名称" :filters="activityFilters" :filter-method="filterByactivity">
                <template #default="scope">
                  <span>{{ scope.row.aname }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="cname" label="社团" :filters="clubFilters2" :filter-method="filterByClub2">
                <template #default="scope">
                  <span>{{ scope.row.cname }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="ApprovalState2 === 0">
                <template v-slot="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-button @click="openDialog2(row, 'approve')" type="primary">批准</el-button>
                    <el-button @click="openDialog2(row, 'reject')" type="danger">拒绝</el-button>
                  </div>

                 
                </template>
              </el-table-column>
              <el-table-column label="审批结果" v-if="ApprovalState2 === 1" :filters="approvalFilters"
                               :filter-method="filterByApprovalResult">
                <template v-slot="{ row }">
                  <el-tag v-if="row.approval_state === 1" type="success">已通过</el-tag>
                  <el-tag v-if="row.approval_state === 2" type="danger">已拒绝</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog   v-model="dialogVisible2"  title="备注" @close="handleclose">
              <el-input type="textarea" v-model="joinactivity.remark"></el-input>
              <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancelJoinActivityApprove">取 消</el-button>
                <el-button type="primary" @click="submitForm2">确 定</el-button>
              </span>
              </template>
            </el-dialog>
          </div>
          <div v-else>
            暂时没有加入活动申请
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="退社申请" name="quitClub">
        <div v-if="loading3">数据加载中...</div>
        <div v-if="!loading3">
          <div v-if="QuitClubApplies.length>0" style="display: flex;flex-direction: column;">
            <div style="display: flex;justify-content:flex-start;align-items:center;margin:10px">
              <div style="margin-left:10px;margin-right:10px ">
                <el-select v-model="ApprovalState3" placeholder="未审批" @change="getQuitClubApplies" style="width:150px;marigin:10px">
                  <el-option label="未审批" :value="0"></el-option>
                  <el-option label="已审批" :value="1"></el-option>
                </el-select>
              </div>
              <el-button v-if="ApprovalState3 === 0" type="primary" @click="approveSelectedApplies('approve',6)">一键批准所选</el-button>
              <el-button v-if="ApprovalState3 === 0" type="primary" @click="approveSelectedApplies('reject',6)">一键拒绝所选</el-button>
            </div>
            <el-table
                ref="quitClubTable"
                :data="filteredQuitClub"
                :default-sort="{ prop: 'applyTime', order: 'descending' }"
                style="width: 1120px"
            >
              <el-table-column type="selection" width="55" v-if="ApprovalState3 === 0"></el-table-column>
              <el-table-column
                  type="index"
                  width="50">
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" sortable :formatter="DatetoUser"></el-table-column>
              <el-table-column prop="uid" label="用户ID" ></el-table-column>
              <el-table-column prop="uname" label="用户名" ></el-table-column>
              <el-table-column prop="cname" label="社团" :filters="clubFilters3" :filter-method="filterByClub3">
                <template #default="scope">
                  <span>{{ scope.row.cname }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="申请理由"></el-table-column>
              <el-table-column label="操作" v-if="ApprovalState3 === 0">
                <template v-slot="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-button @click="openDialog3(row, 'approve')" type="primary">批准</el-button>
                    <el-button @click="openDialog3(row, 'reject')" type="danger">拒绝</el-button>
                  </div>
                  
                </template>
              </el-table-column>
              <el-table-column label="审批结果" v-if="ApprovalState3 === 1" :filters="approvalFilters"
                               :filter-method="filterByApprovalResult">
                <template v-slot="{ row }">
                  <el-tag v-if="row.approval_state === 1" type="success">已通过</el-tag>
                  <el-tag v-if="row.approval_state === 2" type="danger">已拒绝</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog   v-model="dialogVisible3"  title="备注" @close="handleclose">
              <el-input type="textarea" v-model="quitclub.remark"></el-input>
              <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancelQuitClubApprove">取 消</el-button>
                <el-button type="primary" @click="submitForm3">确 定</el-button>
              </span>
              </template>
            </el-dialog>
          </div>
          <div v-else>
            暂时没有退社申请
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  <!-- </div> -->
</template>

<script>
import {onMounted, reactive, ref} from 'vue';
import axios from "axios";
import {useStore} from "vuex";
import {ElMessage} from "element-plus";
import {downloadFile} from "@/utils/fileTool";

export default {
    methods: {
      handleDownload(fileUrl, fileName) {
        downloadFile(fileUrl,fileName)
      },
  },
  setup() {
    const activeTab = ref('joinClub');
    const joinClubTable = ref(null);
    const joinActivityTable=ref(null);
    const quitClubTable=ref(null);
    const store = useStore();

    const loading1=ref(true);
    const loading2=ref(true);
    const loading3=ref(true);
    const joinClubApplies = ref([]);
    const clubFilters1 = ref([]);
    const dialogVisible1 = ref(false);
    const ApprovalState1=ref(0);
    const filteredjoinClub=ref([]);

    const joinActivityApplies = ref([]);
    const clubFilters2   = ref([]);const activityFilters=ref([]);
    const dialogVisible2 = ref(false);
    const ApprovalState2=ref(0);
    const filteredjoinActivity=ref([]);

    const QuitClubApplies = ref([]);
    const clubFilters3   = ref([]);
    const dialogVisible3 = ref(false);
    const ApprovalState3=ref(0);
    const filteredQuitClub=ref([]);

    const approvalFilters = ref([
      { text: '全部', value: 0 },
      { text: '已通过', value: 1 },
      { text: '已拒绝', value: 2 }
    ]);
    const filterByApprovalResult = (value, row) => {
      if (value === 0) return true;
      return row.approval_state === value;
    };
    const formatDate=(time)=> {
          var year = time.getFullYear(); // 年
          var month = (time.getMonth() + 1).toString().padStart(2, '0'); // 月
          var date = time.getDate().toString().padStart(2, '0'); // 日
          var hour = time.getHours().toString().padStart(2, '0'); // 时
          var minute = time.getMinutes().toString().padStart(2, '0'); // 分
          var second = time.getSeconds().toString().padStart(2, '0'); // 秒
          return (
              year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
          )
    };
    const DatetoUser = (row, column) => {
      const date = new Date(row[column.property]);
      const year = date.getUTCFullYear();
      const month = (date.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以要加1
      const day = date.getUTCDate().toString().padStart(2, '0');
      const hours = date.getUTCHours().toString().padStart(2, '0'); // 获取小时
      const minutes = date.getUTCMinutes().toString().padStart(2, '0'); // 获取分钟
      const seconds = date.getUTCSeconds().toString().padStart(2, '0'); // 获取秒数
      return `${year}-${month}-${day}  ${hours}:${minutes}:${seconds}`;
    };



    const joinclub = reactive({
      action: '',
      remark: '',
      row: null
    });
    const joinactivity = reactive({
      action: '',
      remark: '',
      row: null
    });
    const quitclub = reactive({
      action: '',
      remark: '',
      row: null
    });
    // 打开对话框，每种申请不一样
    const openDialog1 = (row, action) => {
      joinclub.action = action;
      joinclub.row = row;
      dialogVisible1.value = true;
    }
    const openDialog2 = (row, action) => {
      joinactivity.action = action;
      joinactivity.row = row;
      dialogVisible2.value = true;
    }
    const openDialog3 = (row, action) => {
      quitclub.action = action;
      quitclub.row = row;
      dialogVisible3.value = true;
    }

    // 提交表单,每种申请不一样
    const submitForm1 = async () => {
      dialogVisible1.value = false;
      try {
        await approveApplication(joinclub.row, joinclub.remark,joinclub.action, 0);
        if (joinclub.action === 'approve') {
          ElMessage.success('申请已批准');
        } else if (joinclub.action === 'reject') {
          ElMessage.success('申请已拒绝');
        }
      } catch (error) {
        ElMessage.error("申请审批失败")
      }
      joinclub.remark='';
    }
    const cancelJoinClubApprove=()=>{
      dialogVisible1.value=false;
      joinclub.remark='';
    }

    const submitForm2 = async () => {
      dialogVisible2.value = false;
      try {
        await approveApplication(joinactivity.row, joinactivity.remark,joinactivity.action, 1);
        if (joinactivity.action === 'approve') {
          ElMessage.success('申请已批准');
        } else if (joinactivity.action === 'reject') {
          ElMessage.success('申请已拒绝');
        }
      } catch (error) {
        ElMessage.error("申请审批失败")
      }
      joinactivity.remark='';
    }
    const cancelJoinActivityApprove=()=>{
      dialogVisible2.value=false;
      joinactivity.remark='';
    }

    const submitForm3 = async () => {
      dialogVisible3.value = false;
      try {
        await approveApplication(quitclub.row, quitclub.remark,quitclub.action, 6);
        if (quitclub.action === 'approve') {
          ElMessage.success('申请已批准');
        } else if (quitclub.action === 'reject') {
          ElMessage.success('申请已拒绝');
        }
      } catch (error) {
        ElMessage.error("申请审批失败")
      }
      quitclub.remark='';
    }
    const cancelQuitClubApprove=()=>{
      dialogVisible3.value=false;
      quitclub.remark='';
    }
    const approveSelectedApplies=async (action,kind) => {
      let selectedRows = [];
      if (kind === 0){
        selectedRows = joinClubTable.value?.getSelectionRows() || [];
      }else if(kind === 1){
        selectedRows = joinActivityTable.value?.getSelectionRows() || [];
      }else if(kind === 6){
        selectedRows = quitClubTable.value?.getSelectionRows() || [];
      }
      if (selectedRows.length === 0) {
        ElMessage.warning('请先选择要审批的申请');
        return;
      }
      let successCount = 0;
      let failureCount = 0;
      for (const row of selectedRows) {
        try {
          await approveApplication(row, '', action, kind);
          successCount++;
        } catch (error) {
          failureCount++;
        }
      }

      if (successCount > 0) {
        ElMessage.success(`成功批准 ${successCount} 个申请`);
      }

      if (failureCount > 0) {
        ElMessage.error(`有 ${failureCount} 个申请审批失败`);
      }
    }
    // 生成社团筛选项,根据社团名称筛选方法
    function generateclubFilters1() {
      const clubs = new Set(filteredjoinClub.value.map(app => app.cname));
      clubFilters1.value = Array.from(clubs).map(club => ({ text: club, value: club }));
    }
    const filterByClub1=(value, row)=>{
      return row.cname === value;
    }

    function generateclubFilters2() {
      const clubs = new Set(filteredjoinActivity.value.map(app => app.cname));
      clubFilters2.value = Array.from(clubs).map(club => ({ text: club, value: club }));
    }
    const filterByClub2=(value, row)=>{
      return row.cname === value;
    }
    function generateactivityFilters() {
      const clubs = new Set(filteredjoinActivity.value.map(app => app.aname));
      activityFilters.value = Array.from(clubs).map(club => ({ text: club, value: club }));
    }
    const filterByactivity=(value, row)=>{
      return row.aname === value;
    }
    function generateclubFilters3() {
      const clubs = new Set(filteredQuitClub.value.map(app => app.cname));
      clubFilters3.value = Array.from(clubs).map(club => ({ text: club, value: club }));
    }
    const filterByClub3=(value, row)=>{
      return row.cname === value;
    }

    // 批准申请方法，适用于每种申请
    const approveApplication = async (row, remark,action,kind) => {
      const formData = new FormData()
      var getTime = new Date().getTime(); //获取到当前时间戳
      var time = new Date(getTime); //创建一个日期对象
      var currenttime=formatDate(time)
      formData.append('permission',store.state.userinfo.permission)
      formData.append('kind',kind)
      formData.append('id',row.id)
      formData.append("action",action)
      formData.append('apply_id',row.apply_id)
      formData.append('uid',row.uid)
      formData.append('aid',row.aid)
      formData.append('cid',row.cid)
      formData.append('remark',remark)
      formData.append('approval_time',currenttime)
      formData.append('cname',row.cname)
      formData.append('aname',row.aname)
      formData.append('approver',store.state.userinfo.account)
      try {
        const response = await axios.post('/api/approval/ApproveApplies', formData);

        if (kind === 0) {
          filteredjoinClub.value = filteredjoinClub.value.filter(club => club.id !== row.id);
        } else if (kind === 1) {
          filteredjoinActivity.value = filteredjoinActivity.value.filter(activity => activity.id !== row.id);
        } else if (kind === 6) {
          filteredQuitClub.value = filteredQuitClub.value.filter(quitClub => quitClub.id !== row.id);
        }

        console.log(response);
      } catch (error) {
        console.error(error);
        throw new Error('审批失败');
      }
    }
    // 获取入社申请
    const getjoinClubApplies =async() => {
      loading1.value=true;
      console.log("account:",store.state.userinfo.account)
      axios.get('/api/approval/joinClubApplies', {
        params: {
          account: store.state.userinfo.account
        }
      })
          .then(response => {
            if(response.data.data.clubs){
              joinClubApplies.value = response.data.data.clubs
              console.log("获得入社审批",response.data.data);
              filteredjoinClub.value = joinClubApplies.value.filter(clubs => {
                if(ApprovalState1.value==0) return clubs.approval_state === 0;
                else return clubs.approval_state === 1 || clubs.approval_state === 2;
              });
              generateclubFilters1();
            }
          })
          .catch(function (err) {
            ElMessage.error("获得入社申请失败")
            console.log('获得申请社团审批失败' + err)
          })
          .finally(() => {
            loading1.value = false;
          });
    };
    // 获取加入活动申请
    const getJoinActivityApplies =async() => {
      loading2.value = true;
      console.log("account:",store.state.userinfo.account)
      axios.get('/api/approval/joinActivityApplies', {
        params: {
          account: store.state.userinfo.account
        }
      })
          .then(response => {
            if(response.data.data.activities){
              joinActivityApplies.value = response.data.data.activities;
              console.log("获得加入活动审批",response.data.data);
              filteredjoinActivity.value = joinActivityApplies.value.filter(activities => {
                if(ApprovalState2.value==0) return activities.approval_state === 0;
                else return activities.approval_state === 1 || activities.approval_state === 2;
              });
              generateclubFilters2();
              generateactivityFilters();
            }

          })
          .catch(function (err) {
            ElMessage.error("获得加入活动申请失败")
            console.log('获得加入活动审批失败????????' + err)
          })
          .finally(() => {
            loading2.value = false;
          });
    };
    // 获取退社申请
    const getQuitClubApplies =async() => {
      loading3.value = true;
      console.log("account:",store.state.userinfo.account)
      axios.get('/api/approval/QuitClubApplies', {
        params: {
          account: store.state.userinfo.account
        }
      })
          .then(response => {
            if(response.data.data.qclubs){
              QuitClubApplies.value = response.data.data.qclubs;
              console.log("获得退社审批",response.data.data);
              filteredQuitClub.value = QuitClubApplies.value.filter(qclubs => {
                if(ApprovalState3.value==0) return qclubs.approval_state === 0;
                else return qclubs.approval_state === 1 || qclubs.approval_state === 2;
              });
              generateclubFilters3();
            }
          })
          .catch(function (err) {
            ElMessage.error("获得退社申请失败")
            console.log('获得退社申请失败' + err)
          })
          .finally(() => {
            loading3.value = false;
          });
      console.log("loading3.value",loading3.value)
    };

    const handleclose=()=>{
      joinclub.remark='';
      quitclub.remark='';
      joinactivity.remark='';
    }



    onMounted(() => {
      getjoinClubApplies();
      getJoinActivityApplies();
      getQuitClubApplies();
    });


    return {
      handleclose,
      activeTab,
      DatetoUser,formatDate,
      approvalFilters,filterByApprovalResult,
      approveApplication,
      loading1,loading2,loading3,
      joinActivityTable, quitClubTable, joinClubTable,

      ApprovalState1,
      joinClubApplies,filteredjoinClub,
      getjoinClubApplies,
      joinclub,
      cancelJoinClubApprove,
      submitForm1,
      approveSelectedApplies,
      dialogVisible1,
      openDialog1,
      clubFilters1,filterByClub1,
      activityFilters,filterByactivity,
      ApprovalState2,
      joinActivityApplies,filteredjoinActivity,
      getJoinActivityApplies,
      joinactivity,
      cancelJoinActivityApprove,
      submitForm2,
      dialogVisible2,
      openDialog2,
      clubFilters2,filterByClub2,

      ApprovalState3,
      QuitClubApplies,filteredQuitClub,
      getQuitClubApplies,
      quitclub,
      cancelQuitClubApprove,
      submitForm3,
      dialogVisible3,
      openDialog3,
      clubFilters3,filterByClub3,
    };
  },
};
</script>

<style scoped>
.el-table {
  overflow-y: auto !important;
  overflow-x: auto !important;
}

</style>
